import base64
import pickle

from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request, user, response):
    """
    登录后合并cookie购物车数据到redis
    :param request: 本次请求对象，获取cookie中的数据
    :param response: 本次响应对象，清除cookie中的数据
    :param user: 登录用户信息，获取user_id
    :return: response
    """
    # 获取cookie的购物车对象
    cart_cookie = request.COOKIES.get('cart')
    # 如果没有数据 返回response
    if not cart_cookie:
        return response
    # 把数据解码转为字典
    cookie_cart_dict = pickle.loads(base64.b64decode(cart_cookie.encode()))

    # 把购物车字典数据转为保存redis的字典的格式
    new_cart_dict = {}
    new_cart_selected_add= []
    new_cart_selected_rm = []
    for sku_id, cookie_value_dict in cookie_cart_dict.items():
        # 按照{sku_id2:2,sku_id3:3}储存
        new_cart_dict[sku_id] = cookie_value_dict['count']
        # 判断当前商品是否选中
        if cookie_value_dict['selected']:
            new_cart_selected_add.append(sku_id)
        else:
            new_cart_selected_rm.append(sku_id)

    # 把转完格式的数据保存到redis hash
    redis_conn = get_redis_connection('carts')
    pl = redis_conn.pipeline()
    # 这里不会删除原来的数据，只会覆盖相同key的数据
    pl.hmset('cart_%s' % user.id, new_cart_dict)

    # 修改是否选中商品的状态 set
    if new_cart_selected_add:
        pl.sadd('selected_%s' % user.id, *new_cart_selected_add)

    if new_cart_selected_rm:
        pl.srem('selected_%s' % user.id, *new_cart_selected_rm)
    pl.execute()
    # 删除cookie数据
    response.delete_cookie('cart')
    # 返回响应
    return response